﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Threading;

public partial class SystemManage_ClientEdit : BasePage
{
     ISyClientHandler clientManage = new SyClientHandler();
     ISyPlaceHandler placeManage = new SyPlaceHandler();
     private static int num = -1;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!(strPermission.Contains("1035") || strPermission.Contains("1036")))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
            }

            ViewState["OrderBy"] = "RowNum";
            ViewState["Accending"] = "asc";
            FillDll();
            dataBind();
        }
    }



    private void dataBind()
    {
       
        DataTable dtLinkMan = new DataTable();
        if (ViewState["LinkMan"] != null)
        {
            divEntrust.Visible = true;
            dtLinkMan = (DataTable)ViewState["LinkMan"];

            DataView view = dtLinkMan.DefaultView;
            view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
            gvClientList.DataSource = view;
            gvClientList.DataBind();
            if (dtLinkMan != null && dtLinkMan.Rows.Count > 0)
            {
                lblTotal.Text = dtLinkMan.Rows.Count.ToString();
            }
            else
            {
                lblTotal.Text = "0";
            }

        }
        else
        {
            divEntrust.Visible = false;
        }      
    }

    private void FillDll()
    {
        DataTable dt = placeManage.GetList();
        ddlPlace.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlPlace.DataTextField = "ENGName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlPlace.DataTextField = "HKName";
        }
        else
        {
            ddlPlace.DataTextField = "Name";
        }
        ddlPlace.DataValueField = "PKID";
        ddlPlace.DataBind();

        ddlPlace.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        DataTable dtT = clientManage.GetClientTypeList();
        if (dtT != null && dtT.Rows.Count > 0)
        {
            chkClientList.DataSource = dtT;
            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
            {
                chkClientList.DataTextField = "ENGName";
            }
            else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                chkClientList.DataTextField = "HKName";
            }
            else
            {
                chkClientList.DataTextField = "Name";
            }
            chkClientList.DataValueField = "PKID";
            chkClientList.DataBind();
        }

        IRolePurviewHandler userManager = new RolePurviewHandler();
        string sql = "select * from users where ClientID = @Company";
        SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@Company", "0") };

        ddlCompanyBP.DataSource = userManager.GetUsersList(sql, parms);
        ddlCompanyBP.DataTextField = "LoginID";
        ddlCompanyBP.DataValueField = "UserID";
        ddlCompanyBP.DataBind();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {

        SqlParameter[] parms = null;
        List<SqlParameter> list = new List<SqlParameter>();
        string sqlStr = string.Empty;
        StringBuilder sb = new StringBuilder();
        foreach (ListItem item in chkClientList.Items)
        {
            if (item.Selected)
            {
                sb.Append(item.Value + ",");
            }
        }
        string permission = sb.ToString();
        string[] clientTypes = null;

        if (permission.Length > 0)
        {
            permission = permission.Substring(0, permission.Length - 1);
            clientTypes = permission.Split(new char[] { ',' });
        }
        else
        {
            Jscript.Alert(Resources.Messages.ClientTypeEmpty, this.Page);
            return;
        }

        if (Request["PKID"] == null)
        {

            //DataTable dtClient = clientManage.GetClientListByCode(txtCode.Text.Trim());
            //if (dtClient != null && dtClient.Rows.Count > 0)
            //{
            //    Jscript.Alert(Resources.Messages.CodeExists, this.Page);
            //    return;
            //}
            //  parms = new SqlParameter[41];
            SqlParameter parm = new SqlParameter("@ReturnValue",0);
            parm.SqlDbType = SqlDbType.Int;
            parm.Direction = ParameterDirection.Output;
            list.Add(parm);
            list.Add(new SqlParameter("@Code", string.Empty));

            sqlStr = @"INSERT INTO Sy_Client(Code,CNShortName,ENGShortName,CNName,ENGName,CNAddress,ENGAddress,Title,Email,WebSite,
                          PShiper,CompanyBP,Place,BRLinkMan,BRTelNo,BRFax,BRMPhone,FRLinkMan,FRTelNo,FRFax,FRBank,FRAccount,HKBROffice,
                          HKBRTelNo,HKBREmail,HKBRLinkMan,HKBRFax,HKBRCustoms,LRHKLinkMan,LRHKTelNo,LRHKFax,LRHKEmail,LRSZLinkMan,
                          LRSZTelNo,LRSZFax,LRSZEmail,Remark,Status,LastModUser,LastModDate,HKShortName,HKName,HKAddress,ENGTitle,HKTitle,PlaceID,MVendorCode,HVendorCode,ToYantian,ToShekou,GPSWebsite) VALUES(@Code,@CNShortName,@ENGShortName,@CNName,@ENGName,@CNAddress,@ENGAddress,@Title,@Email,@WebSite,
                          @PShiper,@CompanyBP,@Place,@BRLinkMan,@BRTelNo,@BRFax,@BRMPhone,@FRLinkMan,@FRTelNo,@FRFax,@FRBank,@FRAccount,@HKBROffice,
                          @HKBRTelNo,@HKBREmail,@HKBRLinkMan,@HKBRFax,@HKBRCustoms,@LRHKLinkMan,@LRHKTelNo,@LRHKFax,@LRHKEmail,@LRSZLinkMan,
                          @LRSZTelNo,@LRSZFax,@LRSZEmail,@Remark,@Status,@LastModUser,@LastModDate,@HKShortName,@HKName,@HKAddress,@ENGTitle,@HKTitle,@PlaceID,@MVendorCode,@HVendorCode,@ToYantian,@ToShekou,@GPSWebsite) SET @ReturnValue=@@Identity;";
            for (int i = 0; i < clientTypes.Length; i++)
            {
                list.Add(new SqlParameter("@SyCodeID" + i.ToString(), clientTypes[i]));
                sqlStr += "INSERT INTO Sy_ClientType(ClientID,SyCodeID) VALUES(@ReturnValue,@SyCodeID" + i.ToString() + ");";
            }

            //添加联系人


            if (ViewState["LinkMan"] != null)
            {
                DataTable dt = (DataTable)ViewState["LinkMan"];
                if (dt != null && dt.Rows.Count > 0)
                {                                     

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                      
                        list.Add(new SqlParameter("@LinkMan" + i.ToString(), dt.Rows[i]["LinkMan"].ToString()));
                        list.Add(new SqlParameter("@LTelNo" + i.ToString(), dt.Rows[i]["TelNo"].ToString()));
                        list.Add(new SqlParameter("@LMPhone" + i.ToString(), dt.Rows[i]["MPhone"].ToString()));
                        list.Add(new SqlParameter("@LFax" + i.ToString(), dt.Rows[i]["Fax"].ToString()));

                        list.Add(new SqlParameter("@LEmail" + i.ToString(), dt.Rows[i]["Email"].ToString()));
                        list.Add(new SqlParameter("@LPosition" + i.ToString(), dt.Rows[i]["Position"].ToString()));
                        list.Add(new SqlParameter("@LAddress" + i.ToString(), dt.Rows[i]["Address"].ToString()));
                        list.Add(new SqlParameter("@LRemark" + i.ToString(), dt.Rows[i]["Remark"].ToString()));


                        sqlStr += @"INSERT INTO Sy_ClientLinkMan(ClientID,LinkMan,TelNo,MPhone,Fax,Email,Position,Address,Remark)
                               VALUES(@ReturnValue,@LinkMan" + i.ToString() + ",@LTelNo" + i.ToString() + ",@LMPhone" + i.ToString() + ",@LFax" + i.ToString() + ",";

                        sqlStr += "@LEmail" + i.ToString() + ",@LPosition" + i.ToString() + ",@LAddress" + i.ToString() + ",@LRemark" + i.ToString() + ")";
                    }
                }
            }



        }
        else
        {
            // parms = new SqlParameter[40];
            list.Add(new SqlParameter("@PKID", Request["PKID"]));
            sqlStr = @"UPDATE Sy_Client SET CNShortName=@CNShortName,ENGShortName=@ENGShortName,CNName=@CNName,ENGName=@ENGName,CNAddress=@CNAddress,ENGAddress=@ENGAddress,Title=@Title,Email=@Email,WebSite=@WebSite,
                          PShiper=@PShiper,CompanyBP=@CompanyBP,Place=@Place,BRLinkMan=@BRLinkMan,BRTelNo=@BRTelNo,BRFax=@BRFax,BRMPhone=@BRMPhone,FRLinkMan=@FRLinkMan,FRTelNo=@FRTelNo,FRFax=@FRFax,FRBank=@FRBank,FRAccount=@FRAccount,HKBROffice=@HKBROffice,
                          HKBRTelNo=@HKBRTelNo,HKBREmail=@HKBREmail,HKBRLinkMan=@HKBRLinkMan,HKBRFax=@HKBRFax,HKBRCustoms=@HKBRCustoms,LRHKLinkMan=@LRHKLinkMan,LRHKTelNo=@LRHKTelNo,LRHKFax=@LRHKFax,LRHKEmail=@LRHKEmail,LRSZLinkMan=@LRSZLinkMan,
                          LRSZTelNo=@LRSZTelNo,LRSZFax=@LRSZFax,LRSZEmail=@LRSZEmail,Remark=@Remark,Status=@Status,LastModUser=@LastModUser,LastModDate=@LastModDate WHERE PKID=@PKID;";


            sqlStr += "DELETE FROM Sy_ClientType WHERE ClientID=@PKID;";
            for (int i = 0; i < clientTypes.Length; i++)
            {
                list.Add(new SqlParameter("@SyCodeID" + i.ToString(), clientTypes[i]));
                sqlStr += "INSERT INTO Sy_ClientType(ClientID,SyCodeID) VALUES(@PKID,@SyCodeID" + i.ToString() + ");";
            }
        }

        list.Add(new SqlParameter("@CNShortName", txtNameCNS.Text.Trim()));
        list.Add(new SqlParameter("@ENGShortName", txtNameENS.Text.Trim()));
        list.Add(new SqlParameter("@CNName", txtNameCN.Text.Trim()));
        list.Add(new SqlParameter("@ENGName", txtNameEN.Text.Trim()));
        list.Add(new SqlParameter("@CNAddress", txtAddrCN.Text.Trim()));
        list.Add(new SqlParameter("@ENGAddress", txtAddrEN.Text.Trim()));
        list.Add(new SqlParameter("@Title", string.Empty));
        list.Add(new SqlParameter("@Email", txtEmail.Text.Trim()));
        list.Add(new SqlParameter("@WebSite", txtWebsite.Text.Trim()));
        list.Add(new SqlParameter("@PShiper", txtPShiper.Text.Trim()));
        list.Add(new SqlParameter("@CompanyBP", ddlCompanyBP.SelectedValue));
        list.Add(new SqlParameter("@Place", string.Empty));

        list.Add(new SqlParameter("@BRLinkMan", string.Empty));
        list.Add(new SqlParameter("@BRTelNo", string.Empty));
        list.Add(new SqlParameter("@BRFax", string.Empty));
        list.Add(new SqlParameter("@BRMPhone", string.Empty));

        list.Add(new SqlParameter("@FRLinkMan", string.Empty));
        list.Add(new SqlParameter("@FRTelNo", string.Empty));
        list.Add(new SqlParameter("@FRFax", string.Empty));
        list.Add(new SqlParameter("@FRBank", string.Empty));
        list.Add(new SqlParameter("@FRAccount", string.Empty));

        list.Add(new SqlParameter("@HKBROffice", string.Empty));
        list.Add(new SqlParameter("@HKBRTelNo", string.Empty));
        list.Add(new SqlParameter("@HKBREmail", string.Empty));
        list.Add(new SqlParameter("@HKBRLinkMan", string.Empty));
        list.Add(new SqlParameter("@HKBRFax", string.Empty));
        list.Add(new SqlParameter("@HKBRCustoms", string.Empty));

        list.Add(new SqlParameter("@LRHKLinkMan",  string.Empty));
        list.Add(new SqlParameter("@LRHKTelNo", string.Empty));
        list.Add(new SqlParameter("@LRHKFax", string.Empty));
        list.Add(new SqlParameter("@LRHKEmail", string.Empty));

        list.Add(new SqlParameter("@LRSZLinkMan", string.Empty));
        list.Add(new SqlParameter("@LRSZTelNo", string.Empty));
        list.Add(new SqlParameter("@LRSZFax", string.Empty));
        list.Add(new SqlParameter("@LRSZEmail", string.Empty));
        list.Add(new SqlParameter("@Remark", txtRemark.Text.Trim()));

        list.Add(new SqlParameter("@HKShortName", txtNameHKS.Text.Trim()));
        list.Add(new SqlParameter("@HKName", txtNameHK.Text.Trim()));
        list.Add(new SqlParameter("@HKAddress", txtAddrHK.Text.Trim()));
        list.Add(new SqlParameter("@ENGTitle", string.Empty));
        list.Add(new SqlParameter("@HKTitle", string.Empty));
        list.Add(new SqlParameter("@PlaceID", ddlPlace.SelectedValue));

        list.Add(new SqlParameter("@MVendorCode",txtMVendorCode.Text.Trim()));
        list.Add(new SqlParameter("@HVendorCode",txtHVendorCode.Text.Trim()));
        list.Add(new SqlParameter("@ToYantian", txtToYantian.Text.Trim()!=string.Empty? txtToYantian.Text :"0"));
        list.Add(new SqlParameter("@ToShekou",txtToShekou.Text.Trim() !=string.Empty? txtToShekou.Text:"0"));
        list.Add(new SqlParameter("@GPSWebsite",txtGpsWebsite.Text.Trim()));

        if (radYes.Checked)
        {
            list.Add(new SqlParameter("@Status", "1"));
        }
        else
        {
            list.Add(new SqlParameter("@Status", "0"));

        }
        if (Session["UserID"] != null)
        {
            list.Add(new SqlParameter("@LastModUser", Session["UserID"].ToString()));
        }
        else
        {
            list.Add(new SqlParameter("@LastModUser", "0"));

        }
        list.Add(new SqlParameter("@LastModDate", DateTime.Now.ToString("yyyy-MM-dd")));

        parms = list.ToArray();

        if (clientManage.ClientEdit(sqlStr, parms))
        {
            if (Request["PKID"] == null)
            {
                Jscript.AlertAndRedirect(Resources.Messages.AddSuccess, "ClientList.aspx", this.Page);
            }
            else
            {
                Jscript.AlertAndRedirect(Resources.Messages.UpdateSuccess, "ClientList.aspx", this.Page);
            }
        }
        else
        {
            if (Request["PKID"] == null)
            {
                Jscript.Alert(Resources.Messages.AddFailed, this.Page);
            }
            else
            {
                Jscript.Alert(Resources.Messages.UpdateFailed, this.Page);
            }
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect("ClientList.aspx");

    }



    protected void btnAddLinkMan_Click(object sender, EventArgs e)
    {

        DataTable dt = new DataTable();
              
        if (ViewState["LinkMan"] == null)//新建第一条数据
        {
            dt.Columns.Add("RowNum");
            dt.Columns.Add("LinkMan");
            dt.Columns.Add("TelNo");
            dt.Columns.Add("MPhone");
            dt.Columns.Add("Fax");
            dt.Columns.Add("Email");
            dt.Columns.Add("Position");
            dt.Columns.Add("Address");
            dt.Columns.Add("Remark");           


            dt.Rows.Add(new string[] {
                "1",
                 txtLinkMan.Text.Trim(),
                txtPhone.Text.Trim(),
                txtMobile.Text.Trim(),
                txtFax.Text.Trim(),
                txtLEmail.Text.Trim(),               
                txtPosition.Text.Trim(),
                txtAddr.Text.Trim(),
                txtLDesc.Text.Trim()                
            });
        }
        else if (num != -1)//更新缓存的其中一条数据
        {
            dt = (DataTable)ViewState["LinkMan"];
            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    if (i != num - 1)
            //    {
            //        if (dt.Rows[i]["LinkMan"].ToString() == txtLinkMan.Text.Trim())
            //        {
            //            Jscript.Alert("已存在联系人名称为" + txtLinkMan.Text.Trim() + "的记录!");
            //            return;
            //        }
            //    }
            //}

            dt.Rows[(num - 1)]["LinkMan"] = txtLinkMan.Text.Trim();
            dt.Rows[(num - 1)]["TelNo"] = txtPhone.Text.Trim();
            dt.Rows[(num - 1)]["MPhone"] = txtMobile.Text.Trim();
            dt.Rows[(num - 1)]["Fax"] = txtFax.Text.Trim();
            dt.Rows[(num - 1)]["Email"] = txtLEmail.Text.Trim();
            dt.Rows[(num - 1)]["Position"] = txtPosition.Text.Trim();
            dt.Rows[(num - 1)]["Address"] = txtAddr.Text.Trim();
            dt.Rows[(num - 1)]["Remark"] = txtLDesc.Text.Trim();          

        }
        else//添加第二条以上数据
        {
            dt = (DataTable)ViewState["LinkMan"];

            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    if (dt.Rows[i]["LinkMan"].ToString() == txtLinkMan.Text.Trim())
            //    {
            //        Jscript.Alert("已存在联系人名称为" + txtLinkMan.Text.Trim() + "的记录!");
            //        return;
            //    }
            //}
            dt.Rows.Add(new string[] {
                Convert.ToString(dt.Rows.Count+1),
              txtLinkMan.Text.Trim(),
                txtPhone.Text.Trim(),
                txtMobile.Text.Trim(),
                txtFax.Text.Trim(),
                txtLEmail.Text.Trim(),               
                txtPosition.Text.Trim(),
                txtAddr.Text.Trim(),
                txtLDesc.Text.Trim()  
            });
        }

        ViewState["LinkMan"] = dt;
        dataBind();
        Clear();

    }
    protected void gvClientList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvClientList.PageIndex = e.NewPageIndex;
        dataBind();

    }
    protected void gvClientList_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        if (ViewState["LinkMan"] != null)
        {
            DataTable dt = new DataTable();
            if (e.CommandName.ToLower() == "up")
            {
                dt = (DataTable)ViewState["LinkMan"];

                txtLinkMan.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["LinkMan"].ToString();
                txtPhone.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["TelNo"].ToString();
                txtMobile.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["MPhone"].ToString();
                txtFax.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["Fax"].ToString();
                txtLEmail.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["Email"].ToString();
                txtPosition.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["Position"].ToString();
                txtAddr.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["Address"].ToString();
                txtLDesc.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["Remark"].ToString();               
                num = int.Parse(dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["RowNum"].ToString());//给一个静态变量付值。更新哪条数据
              
            }
            else if (e.CommandName.ToLower() == "copy")
            {
                dt = (DataTable)ViewState["LinkMan"];

                txtLinkMan.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["LinkMan"].ToString();
                txtPhone.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["TelNo"].ToString();
                txtMobile.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["MPhone"].ToString();
                txtFax.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["Fax"].ToString();
                txtLEmail.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["Email"].ToString();
                txtPosition.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["Position"].ToString();
                txtAddr.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["Address"].ToString();
                txtLDesc.Text = dt.Rows[(int.Parse(e.CommandArgument.ToString()) - 1)]["Remark"].ToString();
                num = -1;
            }
            else if (e.CommandName.ToLower() == "del")
            {
                dt = (DataTable)ViewState["LinkMan"];
                dt.Rows.RemoveAt((int.Parse(e.CommandArgument.ToString()) - 1));
                dataBind();
            }
        }

    }

    private void Clear()
    {
        txtLinkMan.Text = string.Empty;
        txtPhone.Text = string.Empty;
        txtMobile.Text = string.Empty;
        txtLEmail.Text = string.Empty;
        txtAddr.Text = string.Empty;
        txtLDesc.Text = string.Empty;
        txtFax.Text = string.Empty;
        txtPosition.Text = string.Empty;
        hidPKID.Text = string.Empty;
        num = -1;

    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvClientList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvClientList.PageCount)
            {
                this.gvClientList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvClientList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }

    protected void gvClientList_RowDataBound(object sender, GridViewRowEventArgs e)
    {

    }
    protected void gvClientList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        Clear();
    }
}
